from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import BaseUserManager


class CustomUserManager(BaseUserManager):

    def _create_user(self, external_identifier, password,
                     is_staff, is_superuser, **extra_fields):
        """
        Creates and saves a User with the given external_identifier and password.
        """
        now = timezone.now()
        user = self.model(external_identifier=external_identifier,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, last_login=now,
                          **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, external_identifier, password=None, **extra_fields):
        return self._create_user(external_identifier, password, False, False,
                                 **extra_fields)

    def create_superuser(self, external_identifier, password, **extra_fields):
        return self._create_user(external_identifier, password, True, True,
                                 **extra_fields)

class CustomUser(AbstractBaseUser, PermissionsMixin):

    external_identifier = models.CharField(_('external identifier'), max_length=254, blank=True, unique=True)
    email = models.EmailField(_('email address'), max_length=254)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    is_local = models.BooleanField(_('local user status'), default=False)
    is_active = models.BooleanField(_('staff status'), default=True)
    is_staff = models.BooleanField(_('staff status'), default=False)
    
    objects = CustomUserManager()

    USERNAME_FIELD = 'external_identifier'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):
        return self.get_full_name()

    def get_absolute_url(self):
        return ""

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns the short name for the user."
        return self.first_name